package org.farng.mp3.lyrics3;

import org.farng.mp3.InvalidTagException;
import org.farng.mp3.TagConstant;
import org.farng.mp3.TagOptionSingleton;
import org.farng.mp3.id3.FrameBodySYLT;
import org.farng.mp3.id3.FrameBodyUSLT;
import org.farng.mp3.object.ObjectID3v2LyricLine;
import org.farng.mp3.object.ObjectLyrics3Line;
import org.farng.mp3.object.ObjectLyrics3TimeStamp;

import java.io.RandomAccessFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;


/**
 * Title: Description: Copyright:    Copyright (c) 2002 Company:
 *
 * @author Eric Farng
 * @version $Revision: 1.5 $
 */
public class FieldBodyLYR extends AbstractLyrics3v2FieldBody {
    /** DOCUMENT ME! */
    private ArrayList lines = new ArrayList();

    /**
     * Creates a new FieldBodyLYR object.
     */
    public FieldBodyLYR() {}

    public FieldBodyLYR(FieldBodyLYR copyObject) {
        super(copyObject);

        ObjectLyrics3Line oldObject;

        for (int i = 0; i < copyObject.lines.size(); i++) {
            oldObject = (ObjectLyrics3Line) copyObject.lines.get(i);
            this.lines.add(new ObjectLyrics3Line(oldObject));
        }
    }

    /**
     * Creates a new FieldBodyLYR object.
     *
     * @param line DOCUMENT ME!
     */
    public FieldBodyLYR(String line) {
        readString(line);
    }

    /**
     * Creates a new FieldBodyLYR object.
     *
     * @param sync DOCUMENT ME!
     */
    public FieldBodyLYR(FrameBodySYLT sync) {
        addLyric(sync);
    }

    /**
     * Creates a new FieldBodyLYR object.
     *
     * @param unsync DOCUMENT ME!
     */
    public FieldBodyLYR(FrameBodyUSLT unsync) {
        addLyric(unsync);
    }

    /**
     * Creates a new FieldBodyLYR object.
     *
     * @param file DOCUMENT ME!
     *
     * @throws InvalidTagException DOCUMENT ME!
     * @throws java.io.IOException DOCUMENT ME!
     */
    public FieldBodyLYR(RandomAccessFile file)
                 throws InvalidTagException, java.io.IOException {
        this.read(file);
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public String getIdentifier() {
        return "LYR";
    }

    /**
     * DOCUMENT ME!
     *
     * @param str DOCUMENT ME!
     */
    public void setLyric(String str) {
        readString(str);
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public String getLyric() {
        return writeString();
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public int getSize() {
        int               size = 0;
        ObjectLyrics3Line line;

        for (int i = 0; i < lines.size(); i++) {
            line = (ObjectLyrics3Line) lines.get(i);
            size += (line.getSize() + 2);
        }

        return size;

        //return size - 2; // cut off the last crlf pair
    }

    /**
     * DOCUMENT ME!
     *
     * @param obj DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean isSubsetOf(Object obj) {
        if ((obj instanceof FieldBodyLYR) == false) {
            return false;
        }

        ArrayList superset = ((FieldBodyLYR) obj).lines;

        for (int i = 0; i < lines.size(); i++) {
            if (superset.contains(lines.get(i)) == false) {
                return false;
            }
        }

        return super.isSubsetOf(obj);
    }

    /**
     * DOCUMENT ME!
     *
     * @param sync DOCUMENT ME!
     */
    public void addLyric(FrameBodySYLT sync) {
        // SYLT frames are made of individual lines
        Iterator               iterator = sync.iterator();
        ObjectLyrics3Line      newLine;
        ObjectID3v2LyricLine   currentLine;
        ObjectLyrics3TimeStamp timeStamp;
        HashMap                lineMap = new HashMap();

        while (iterator.hasNext()) {
            currentLine = (ObjectID3v2LyricLine) iterator.next();

            // create copy to use in new tag
            currentLine = new ObjectID3v2LyricLine(currentLine);
            timeStamp   = new ObjectLyrics3TimeStamp("Time Stamp");
            timeStamp.setTimeStamp(currentLine.getTimeStamp(), sync.getTimeStampFormat());

            if (lineMap.containsKey(currentLine.getText())) {
                newLine = (ObjectLyrics3Line) lineMap.get(currentLine.getText());
                newLine.addTimeStamp(timeStamp);
            } else {
                newLine = new ObjectLyrics3Line("Lyric Line");
                newLine.setLyric(currentLine);
                newLine.setTimeStamp(timeStamp);
                lineMap.put(currentLine.getText(), newLine);
                lines.add(newLine);
            }
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param unsync DOCUMENT ME!
     */
    public void addLyric(FrameBodyUSLT unsync) {
        // USLT frames are just long text string;
        ObjectLyrics3Line line = new ObjectLyrics3Line("Lyric Line");
        line.setLyric(new String(unsync.getLyric()));
        lines.add(line);
    }

    /**
     * DOCUMENT ME!
     *
     * @param obj DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean equals(Object obj) {
        if ((obj instanceof FieldBodyLYR) == false) {
            return false;
        }

        FieldBodyLYR object = (FieldBodyLYR) obj;

        if (this.lines.equals(object.lines) == false) {
            return false;
        }

        return super.equals(obj);
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public boolean hasTimeStamp() {
        boolean present = false;

        for (int i = 0; i < lines.size(); i++) {
            if (((ObjectLyrics3Line) lines.get(i)).hasTimeStamp()) {
                present = true;
            }
        }

        return present;
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public Iterator iterator() {
        return lines.iterator();
    }

    /**
     * DOCUMENT ME!
     *
     * @param file DOCUMENT ME!
     *
     * @throws InvalidTagException DOCUMENT ME!
     * @throws java.io.IOException DOCUMENT ME!
     */
    public void read(RandomAccessFile file)
              throws InvalidTagException, java.io.IOException {
        String lineString;

        byte[] buffer = new byte[5];

        // read the 5 character size
        file.read(buffer, 0, 5);

        int size = Integer.parseInt(new String(buffer, 0, 5));

        if ((size == 0) && (TagOptionSingleton.getInstance().isLyrics3KeepEmptyFieldIfRead() == false)) {
            throw new InvalidTagException("Lyircs3v2 Field has size of zero.");
        }

        buffer = new byte[size];

        // read the SIZE length description
        file.read(buffer);
        lineString = new String(buffer);
        readString(lineString);
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    public String toString() {
        String str = getIdentifier() + " : ";

        for (int i = 0; i < lines.size(); i++) {
            str += lines.get(i).toString();
        }

        return str;
    }

    /**
     * DOCUMENT ME!
     *
     * @param file DOCUMENT ME!
     *
     * @throws java.io.IOException DOCUMENT ME!
     */
    public void write(RandomAccessFile file)
               throws java.io.IOException {
        int    size = 0;
        int    offset = 0;
        byte[] buffer = new byte[5];
        String str = "";

        size = getSize();
        str  = Integer.toString(size);

        for (int i = 0; i < (5 - str.length()); i++) {
            buffer[i] = (byte) '0';
        }

        offset += (5 - str.length());

        for (int i = 0; i < str.length(); i++) {
            buffer[i + offset] = (byte) str.charAt(i);
        }

        offset += str.length();
        file.write(buffer, 0, 5);

        if (size > 0) {
            str    = writeString();
            buffer = new byte[str.length()];

            for (int i = 0; i < str.length(); i++) {
                buffer[i] = (byte) str.charAt(i);
            }

            file.write(buffer);
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @param lineString DOCUMENT ME!
     */
    private void readString(String lineString) {
        // now readString each line and put in the vector;
        String token = "";
        int    offset = 0;
        int    delim = lineString.indexOf(TagConstant.CRLF);
        lines = new ArrayList();

        ObjectLyrics3Line line;

        while (delim >= 0) {
            token = lineString.substring(offset, delim);
            line  = new ObjectLyrics3Line("Lyric Line");
            line.setLyric(token);
            lines.add(line);
            offset = delim + TagConstant.CRLF.length();
            delim  = lineString.indexOf(TagConstant.CRLF, offset);
        }

        if (offset < lineString.length()) {
            token = lineString.substring(offset);
            line  = new ObjectLyrics3Line("Lyric Line");
            line.setLyric(token);
            lines.add(line);
        }
    }

    /**
     * DOCUMENT ME!
     *
     * @return DOCUMENT ME!
     */
    private String writeString() {
        ObjectLyrics3Line line;
        String            str = "";

        for (int i = 0; i < lines.size(); i++) {
            line = (ObjectLyrics3Line) lines.get(i);
            str += (line.writeString() + TagConstant.CRLF);
        }

        return str;

        //return str.substring(0,str.length()-2); // cut off the last CRLF pair
    }
}